package com.scw.action;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import com.opensymphony.xwork2.ActionSupport;
import com.scw.model.LinkInfo;
import com.scw.model.SysUser;
import com.scw.service.serviceImp.LinkInfoServiceImpl;
import com.scw.util.CommonNameUtil;
/**
 * 
 * @Description TODO
 * @author 姜武杰
 * @time 2012-9-25
 * @version v1.0
 */
public class LinkImportAction extends ActionSupport {
	protected static LinkInfoServiceImpl linkService;
	private static final long serialVersionUID = 1L;
	private File upload;
	/**
	 * 导出
	 * @return
	 * @throws Exception
	 */
	public String exportLink() throws Exception{
		HttpSession session=ServletActionContext.getRequest().getSession();
		SysUser sysUser=(SysUser) session.getAttribute(CommonNameUtil.SessionUser);
//		List<LinkInfo> linkInfoList = linkService.getLinkInfoByUserId(sysUser.getId());
		List<LinkInfo> linkInfoList = new ArrayList<LinkInfo>();
		StringBuffer htmlContent = new StringBuffer();
		htmlContent.append("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
		htmlContent.append("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">");
		htmlContent.append("<TITLE>Bookmarks</TITLE>");
		htmlContent.append("<H1>Bookmarks</H1>");
		htmlContent.append("<DL><p>");
		for(LinkInfo linkInfo : linkInfoList){
			htmlContent.append("<DT><A HREF=\""+linkInfo.getLinkAddress()+"\" title=\""+linkInfo.getLinkIntro()+"\">"+linkInfo.getLinkTitle()+"</A></DT>");
		}
		htmlContent.append("</DL></p>");
//		OutputStream f0 = new FileOutputStream("D:/test/bookmarks2.html");
		BufferedWriter bwrite=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("D:/test/bookmarks2.html")),"utf-8"));
//		byte[] buf = htmlContent.toString().getBytes("UTF-8");
//		for(int i=0;i<buf.length;i+=2){
//			bwrite.write(buf[i]);
//		}
		bwrite.write(htmlContent.toString());
		bwrite.close();
//		f0.close();
		return null;
	}
	/**
	 * 导入
	 * @return
	 * @throws Exception
	 */
	public String importLink() throws Exception {
		/*InputStream fis = new FileInputStream(getUpload());
		InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		StringBuffer sb = new StringBuffer();
		String str = null;
		// 循环读取一行数据
		while ((str = br.readLine()) != null) {
			// 加入字符
			sb.append(str);
		}
		br.close();
		File file = new File(sb.toString());
		System.out.println(getDocument(file));
		*/
		FileInputStream fin = new FileInputStream(getUpload());
		FileOutputStream fout=new FileOutputStream("D:/test/bookmarks.html");
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		SysUser user = (SysUser) session.getAttribute(CommonNameUtil.SessionUser);
        //定义一个用固暂存数据的byte数组  
        byte [] buff=new byte[256];  
        //每次读取数据的长度  
        int len=0;  
        //循环读取到buff中，如果文件到底，则读取数据的长度小于0  
        while((len=fin.read(buff))>0)  
        {  
            //把数据一次写进输出文件中  
            fout.write(buff,0,len);  
        }  
        //关闭输入流  
        fin.close();  
        //关闭输出流  
        fout.close();  
        File file = new File("D:/test/bookmarks.html");
        getDocument(file,user);
		return null;
	}

	private static String getDocument(File html,SysUser user) {
		String text = "";
		try {
			// 设置编码集
			org.jsoup.nodes.Document doc = Jsoup.parse(html, "UTF-8");
			// 提取标题信息
			Elements hrefLinks = doc.select("a");
			for (org.jsoup.nodes.Element link : hrefLinks) {
				text += link.text() + " ";
				/*System.out.println(link.attr("href") + "、"
						+ link.attr("ADD_DATE") + "、" + link.text());*/
				LinkInfo linkInfo = new LinkInfo();
				linkInfo.setLinkTitle(link.text());
				linkInfo.setLinkAddress(link.attr("href"));
				linkInfo.setIsPrivate("1");
				linkInfo.setLinkIntro(link.text());
				linkInfo.setLinkType("1");
				linkInfo.setShareStatus("2");
				linkService.saveLinkInfo(linkInfo);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return text;
	}
	/**
	 * 
	 *根据用户显示对于的所有收藏
	 *@return String
	 *
	 */
	public String listById(){
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session =request.getSession();
		SysUser sysUser=(SysUser) session.getAttribute(CommonNameUtil.SessionUser);
		List<LinkInfo> list=new ArrayList<LinkInfo>();
//		list=linkService.getLinkInfoByUserId(sysUser.getId());
		request.setAttribute("list", list);
		return "listById";
	}
	
	

	public LinkInfoServiceImpl getLinkService() {
		return linkService;
	}

	public void setLinkService(LinkInfoServiceImpl linkService) {
		this.linkService = linkService;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

}
